--[[
  size = {x1,y1,x2,y2}
  num = 0 ~ 9
  fontLib = 字库
]]
function RxNumber(size, num, fontLibTable)
  local numStr = tostring(num)
  local tab = fontLibTable.num[num + 1]
  RxLog("RxNumber tab=" .. tab[1])
  local ctn, x, y = RxFindText(numStr, numStr, tab, size, fontLibTable.deviationColor, false)
  return ctn, x, y
end

function RxNumberLoopTable(size, fontLibTable)
  local color = fontLibTable.color
  local x1, y1, x2, y2 = size[1], size[2], size[3], size[4]
  local maxx = math.floor((x2 - x1) / 2 + x1)
  local maxy = math.floor((y2 - y1) / 2 + y1)

  local j = y1
  local ctn, lastX1 = 0, x1
  for i=x1,maxx,1 do
    ctn = isColor(i,j, color)
    RxLog('____i='..i..'  ctn='..tostring(ctn))
    if ctn then
      lastX1 = i
      break -- 外层停止
    end
    j = j + 1
  end
  RxLog('.............ctn='..tostring(ctn)..'  lastX1='..lastX1)

  if not ctn then
    return 0, 0
  end

  -- ctn = 0
  j = y2
  local lastX2 = x2
  for i=x2,maxx,-1 do
    ctn = isColor(i,j, color)
    if ctn then
      lastX2 = i
      break -- 外层停止
    end
    j = j - 1
  end

  RxLog('.............ctn='..tostring(ctn)..'lastX2='..lastX2)

  if not ctn then
    return 0, 0
  end

  _newNum = {}
  _index = 1

  local whileLoop = true
  loopx1, loopy1 = lastX1, y1

  while whileLoop do
    loopSize = {loopx1, loopy1, loopx1 + 14, loopy2 + 31}
    -- RxLog("---whileLoop loopx1=" .. loopx1 .. " loopy1=" .. loopy1 .. " loopx2=" .. loopx2 .. " loopy2=" .. loopy2)
    for fonti = 0, 9, 1 do
      local rtn, x, y = RxNumber(loopSize, fonti, fontLibTable)
      if rtn == 1 then
        RxLog("--------fonti=" .. fonti .. " rtn=" .. rtn .. " x=" .. x .. " y=" .. y)
        _newNum[_index] = {id = _index, localtion = x, value = tostring(fonti)}
        _index = _index + 1
        loopx1 = loopx1 + 14
        break
      end
    end

    if loopx1 + 14 >= lastX2 and loopy1 + 31 < maxy then
      loopx1 = lastX1
      loopy1 = loopy1 + 1
    elseif loopx1 + 14 >= lastX2 and loopy1 + 31 >= maxy then
      whileLoop = false
    else
      loopx1 = loopx1 + 1
    end
  end

  table.sort(
    _newNum,
    function(a, b)
      -- 报错：table必须是从1到n连续的，即中间不能有nil，否则会报错
      return a.localtion < b.localtion
    end
  )

  local result = ""
  for _, v in pairs(_newNum) do
    result = result .. v.value
  end

  RxLog("----result-str=" .. result)
  return 1, tonumber(result)
end

function RxNumberGameTop(size)
  return RxNumberLoopTable(size, FontGameTopNum)
end
